package com.example.opentransaction.service;

import com.example.opentransaction.dao.UserMapper;
import com.example.opentransaction.domain.User;
import com.example.opentransaction.domain.UserExample;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class Change1ServiceImpl implements Change1Service{
    @Autowired
    public UserMapper userMapper;

    @Transactional()
    public String change1(Integer userIdOut,Integer userIdIn,Long money){
        Long moneyOut = userMapper.selectByPrimaryKey(userIdOut).getMoney();
        Long moneyIn = userMapper.selectByPrimaryKey(userIdIn).getMoney();

        int n =updateMoney(userIdOut,moneyOut - money);

        int m =updateMoney(userIdIn, moneyIn + money);

        if(n!=0 & m !=0){
            return "转账成功";
        }
        return "转账失败";
    }

    public int updateMoney(Integer userId,Long money){
        User user = new User();
        user.setMoney(money);
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        return userMapper.updateByExampleSelective(user,userExample);
    }
}
